package com.u2ds.core.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Ethan on 2017/6/8.
 */
public class BeanUtil {
    /**
     * 获取类的属性，包括父类
     * @param clazz
     * @return
     */
    public static Map<String, Object> getAllProperties(Object o, Class clazz){
        Map<String, Object> propertyMap = new HashMap<String, Object>();
        if(null == clazz){
            return propertyMap;
        }
        setPropertiesToMap(propertyMap, o, clazz);
        Class superClass = clazz.getSuperclass();
        while(null != superClass){
            setPropertiesToMap(propertyMap, o, superClass);
            superClass = superClass.getSuperclass();
        }
        return propertyMap;
    }

    private static void setPropertiesToMap(Map<String, Object> propertyMap, Object o,  Class clazz){
        Method[] methods = clazz.getDeclaredMethods();
        for(int i = 0; i < methods.length; i++){
            Method method = methods[i];
            if(method.getName().startsWith("get")){
                //只有允许获取的属性才获取，私有属性不获取
                method.setAccessible(true);
                try{
                    Object object = method.invoke(o, null);
                    String upperPropertyName = method.getName().replace("get", "");
                    propertyMap.put(upperPropertyName.substring(0, 1).toLowerCase() + upperPropertyName.substring(1), object);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
